
new Vue({
    el:'#app',
    data:{
        showdownload:false,
        showupload:false,
        showlogon:false,
        showexit:false,
        nologon:true,
        showmsg:false,
        showRecommendationDetail:false,
        notShowSearchResult:true,
        username:'',
        password:'',
        userId:0,
        score:0,
        uploadBookNum:0,
        downloadBookNum:0,
        filename:'',
        booklist:[],
        recommendationlist:[],
        recommendationBookDetail:'',
        downloadinfo:'',
        keyword:'',
        searchresultlist:[],
        today:"",
    },
    created(){

        if(!this.ispc()){
            window.location.href = "out.html"
            console.log("非pc端访问")
        }else{
            //获取今天的年月日和星期
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var a = ["日", "一", "二", "三", "四", "五", "六"];
            var week = a[new Date().getDay()];


            this.today = `${year}年${month}月${strDate}日 星期${week}`;

            if(localStorage.hasOwnProperty("token")){
                this.nologon = false
                this.userId = localStorage.getItem("id")
                this.username = localStorage.getItem("username")
            }
            var that = this

            axios({
                method:'get',
                url: 'http://127.0.0.1:7747/book/home',
            }).then(function(response) {
                let result = response.data
                console.log(result)
                if(result.status == 200){
                    that.booklist = result.data

                    that.$nextTick(()=> {
                        that.reloadPic()
                    })
                }

            })
            axios({
                method:'get',
                url: 'http://127.0.0.1:7747/book/recommendation',
            }).then(function(response) {
                let result = response.data
                console.log(result)
                if (result.status == 200) {
                    that.recommendationlist = result.data
                }
            })

            if(!this.nologon){
                axios({
                    method:'get',
                    url: 'http://127.0.0.1:7747/book/userInfo',
                    params:{
                        userId:that.userId,
                    },
                }).then(function(response) {
                    let result = response.data
                    console.log(result)
                    if (result.status == 200) {
                        that.uploadBookNum = result.data.uploadBookNum
                        that.score = result.data.score
                        that.downloadBookNum = result.data.downloadBookNum
                    }
                })
            }
        }






    },
    mounted(){


    },
    watch:{
        'keyword'(newName,oldName){
            if(newName == ''){
                this.notShowSearchResult = true
                this.showRecommendationDetail = false
                this.$nextTick(()=> {
                    this.reloadPic()
                })
            }
        }
    },
    methods:{
        showDownload:function (bookId, bookName, fileName, downloadNum) {
            this.showdownload = true
            var that = this
            //document.getElementsByClassName("download-tip")[0].innerHTML = "您的浏览器将开始下载《" + bookName + "》"
            this.$nextTick(()=> {
                let box = document.getElementsByClassName("download")
                let appHeight = document.getElementById("app").offsetHeight
                if(box.length > 0){
                    box[0].style.height = appHeight + "px"
                }
                document.getElementsByClassName("download-tip")[0].innerHTML = "您的浏览器将开始下载《" + bookName + "》"
                that.downloadinfo = {
                    fileName : fileName,
                    bookId: bookId,
                    userId : parseInt(that.userId),
                    downloadNum: downloadNum,
                }
            })
        },
        startDownload:function(){
            var that = this
            this.showdownload = false
            axios({
                method: 'post',
                url: 'http://127.0.0.1:7747/book/download',
                data: that.downloadinfo,
                responseType: 'blob' // 表明返回服务器返回的数据类型
            }).then((res) => {

                const content = res

                console.log(content)

                const blob = new Blob([content])

                if ('download' in document.createElement('a')) { // 非IE下载
                    const elink = document.createElement('a')
                    elink.download = that.downloadinfo.fileName
                    elink.style.display = 'none'
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(elink.href) // 释放URL 对象
                    document.body.removeChild(elink)
                } else { // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
            })

        },
        showUpload:function () {
            if(this.nologon){
                this.showmsg = true
                this.$nextTick(()=> {
                    document.getElementById("msg").innerHTML = "请先登录！"
                })
            }else{
                this.showupload = true
                this.$nextTick(()=> {
                    let box = document.getElementsByClassName("download")
                    let appHeight = document.getElementById("app").offsetHeight
                    if(box.length > 0){
                        box[0].style.height = appHeight + "px"
                    }
                })
            }
        },
        showLogon:function () {
            this.showlogon = true
            this.$nextTick(()=> {
                let box = document.getElementsByClassName("download")
                let appHeight = document.getElementById("app").offsetHeight
                if(box.length > 0){
                    box[0].style.height = appHeight + "px"
                }
            })
        },
        login:function () {
            var that = this
            axios({
                method:'get',
                url: 'http://127.0.0.1:7747/user/signin',
                params:{
                    username: that.username,
                    password: that.password,
                },
            }).then(function(response) {
                result = response.data
                if(result.status == 200){

                    that.showlogon = false
                    that.nologon = false
                    that.password = ''
                    that.userId = result.data.id
                    that.score = result.data.score


                    localStorage.setItem("id",result.data.id)
                    localStorage.setItem("username",result.data.username)
                    localStorage.setItem("token",result.data.token)

                }
            })
        },
        exit:function () {
            this.nologon = true
            this.showexit = false
            localStorage.removeItem("id")
            localStorage.removeItem("username")
            localStorage.removeItem("token")
        },
        uploadfile:function () {


            if(this.filename != ''){
                //ajax上传文件
                var formData = new FormData();
                formData.append("bookName",this.filename)
                formData.append("userId",this.userId)
                formData.append("file",this.$refs.fileinput.files[0])
                formData.append("score",this.score)


                // $.ajax({
                //     url:'http://127.0.0.1:7747/book/addBook',
                //     dataType:'json',
                //     type:'POST',
                //     async:false,
                //     data:formData,
                //     processData : false, // 使数据不做处理
                //     contentType : false, // 不要设置Content-Type请求头
                //     success: function(data){
                //         console.log(data);
                //
                //
                //     },
                //     error:function(response){
                //         console.log(response);
                //     }
                // })


                axios.post('http://127.0.0.1:7747/book/addBook',formData,{
                    'Content-Type':'multipart/form-data'
                }).then(res=>{
                    this.showupload = false
                    console.log(res.data)
                    if(res.data.status == 200){
                        this.showmsg = true
                        this.$nextTick(()=> {
                            document.getElementById("msg").innerHTML = "上传成功"
                        })
                    }else{
                        this.showmsg = true
                        this.$nextTick(()=> {
                            document.getElementById("msg").innerHTML = "上传失败"
                        })
                    }
                })

            }else{
                this.showmsg = true
                this.$nextTick(()=> {
                    document.getElementById("msg").innerHTML = "书名不能为空！"
                })

            }


        },
        reloadPic:function(){
            let imgs = document.getElementsByClassName("img")
            let books = document.getElementsByClassName("book-info")
            let covers = document.getElementsByClassName("book-cover")

            for(let i = 0; i < imgs.length; i++){
                let img_url = imgs[i].src
                let img = new Image()
                img.src = img_url

                let realWidth
                // 判断是否有缓存
                if(img.complete){
                    realWidth = parseInt(img.width * 220 / img.height)
                    covers[i].style.width = realWidth + "px"
                    covers[i].style.borderRadius = "3px"
                    let parentWidth = document.getElementsByClassName("books")[0].offsetWidth
                    let bookWidth = parseInt(parentWidth - realWidth) - 5
                    books[i].style.width = bookWidth + "px"
                }else{
                    // 加载完成执行
                    img.onload = function(){
                        realWidth = parseInt(img.width * 220 / img.height)
                        covers[i].style.width = realWidth + "px"
                        covers[i].style.borderRadius = "3px"
                        let parentWidth = document.getElementsByClassName("books")[0].offsetWidth
                        let bookWidth = parseInt(parentWidth - realWidth) - 1
                        books[i].style.width = bookWidth + "px"
                    }

                }
            }
        },
        showRecommendation:function (index) {
            this.showRecommendationDetail = true
            this.recommendationBookDetail = this.recommendationlist[index]
            this.$nextTick(()=> {
                this.reloadPic()
            })
        },
        searchbook:function () {
            var that = this
            axios({
                method:'get',
                url: 'http://127.0.0.1:7747/book/search',
                params:{
                    keyWord:that.keyword,
                },
            }).then(function(response) {
                let result = response.data
                if (result.status == 200) {
                    console.log(result)
                    that.searchresultlist = result.data.content
                    that.notShowSearchResult = false
                    that.showRecommendationDetail = false
                    that.$nextTick(()=> {
                        that.reloadPic()
                    })
                }
            })
        },
        ispc:function() {
            //判断客户端是手机还是电脑
            var userAgentInfo = navigator.userAgent;

            console.log(userAgentInfo)
            var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
            var flag = true;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;
                }
            }
            return flag;
        }

    }
})
